package com.ztools.pc.service.impl.sys;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ztools.common.model.pc.sys.Role;
import com.ztools.common.model.pc.sys.UserRole;
import com.ztools.common.util.common.PageUtil;
import com.ztools.pc.mapper.sys.UserRoleMapper;
import com.ztools.pc.service.sys.RoleService;
import com.ztools.pc.service.sys.UserRoleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author:一口香菜
 * @Date: 2023/3/4  13:18
 * @Version 1.0
 */
@Transactional
@Service
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole> implements UserRoleService {

    @Resource
    private RoleService roleService;
    @Resource
    private UserRoleMapper userRoleMapper;

    @Override
    public Page<UserRole> findList(PageUtil<UserRole> pageUtil) {
        List<OrderItem> orders = new ArrayList<>();
        QueryWrapper<UserRole> queryWrapper = new QueryWrapper<>(pageUtil.getParams());
        Page<UserRole> pages = new Page<>(pageUtil.getPage(), pageUtil.getSize());
        // 排序数据  StrUtil.toUnderlineCase huTools将驼峰装换为下划线格式
        orders.add(new OrderItem(StrUtil.toUnderlineCase(pageUtil.getSortName()), "asc".equals(pageUtil.getSortOrder())));
        pages.setOrders(orders);
        return page(pages, queryWrapper);
    }

    @Override
    public List<UserRole> queryObject(UserRole userRole) {
        QueryWrapper<UserRole> queryWrapper = new QueryWrapper<>(userRole);
        return list(queryWrapper);
    }

    @Override
    public List<Role> findRoleByUserId(Long userId) {
        QueryWrapper<UserRole> userRoleQueryWrapper = new QueryWrapper<>();
        userRoleQueryWrapper.eq("user_id", userId);
        List<UserRole> userRoleList = list(userRoleQueryWrapper);
        if (ArrayUtil.isNotEmpty(userRoleList)) {
            List<Long> roleIds = userRoleList.stream().map(UserRole::getRoleId).collect(Collectors.toList());
            return roleService.findByIds(roleIds);
        }
        return null;
    }

    @Override
    public boolean addList(List<UserRole> userRoles) {
        // 添加前先删除所有角色
        userRoleMapper.deleteByUserId(userRoles.get(0).getUserId());
        if (userRoles.get(0).getRoleId() == null) {
            return true;
        }
        return saveBatch(userRoles);
    }

}
